package cn.hinglo.permission.controller;

import cn.hinglo.common.annotation.IgnorePermission;
import cn.hinglo.common.annotation.IgnoreToken;
import cn.hinglo.common.annotation.RequestMapping;
import cn.hinglo.common.cache.SelfCacheKit;
import cn.hinglo.common.config.base.BaseController;
import cn.hinglo.common.constant.SystemConstant;
import cn.hinglo.common.interceptors.request.Get;
import cn.hinglo.common.interceptors.request.Post;
import cn.hinglo.permission.service.UploadService;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.upload.UploadFile;

import java.io.File;

/**
 * @createTime: 2020/04/22 : 17:39
 * @author: HingLo
 * @description: 文件上传接口
 */
@RequestMapping("/upload")
public class UploadController extends BaseController {

    @Inject
    private UploadService uploadService;

    /***
     * 普通文件上传接口
     * @param type 文件类型
     * @param uploadFile 对剑对象
     */
    @Before(Post.class)
    public void upload(String type, UploadFile uploadFile) {
        String filePath = uploadService.uploadService(type, uploadFile);
        success(filePath);
    }

    /***
     * 图片文件上传接口
     * @param type 文件类型
     * @param uploadFile 文件对象
     */
    @Before(Post.class)
    public void imgUpload(UploadFile uploadFile, String type) {
        String filePath = uploadService.imgUploadService(uploadFile, type);
        success(filePath);
    }

    /***
     * 文件下载
     * @param token token
     */
    @Before(Get.class)
    @IgnoreToken
    @IgnorePermission
    public void download(String token) {
        String filePath = SelfCacheKit.get(SystemConstant.FILE_TOKEN_NAME, token);
        if (StrUtil.isBlank(token) || StrUtil.isBlank(filePath)) {
            error("文件不存在或者链接已失效");
        } else {
            File file = uploadService.downloadService(filePath);
            if (file != null && file.isFile()) {
                renderFile(file);
            } else {
                error("文件不存或者不是一个有效的文件");
            }
        }
    }

}
